﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using System.Mobile.Mvc;
using System.Windows.Forms;
using Microsoft.Practices.Mobile.ContainerModel;
using MultiPanelTest.Data;

namespace MultiPanelTest
{
    public class LoginController : Controller<LoginModel>
    {
        [PublishEvent("OnLogin")]
        public event EventHandler OnLogin;

        public LoginController(IView<LoginModel> view)
            : base(view)
        {

        }

        public Container Container
        {
            get;
            set;
        }


        public void Login()
        {
            if (this.OnLogin != null)
            {
                this.OnLogin(this, EventArgs.Empty);
            }
        }

        protected override void OnInitialize(params object[] parameters)
        {
            this.view.Model = new LoginModel();
            base.OnInitialize(parameters);
        }

        /// <summary>
        /// This method indicates that something has been changed in the view.
        /// </summary>
        /// <param name="key">The string key to identify what has been changed.</param>
        protected override void OnViewStateChanged(string key)
        {
            // Check what's changed
            if (key == "Login")
            {
                // The values are in the ViewData. Let's validate them and return the status to the view
                if (view.Model.User == "Alex" && view.Model.Password == "test")
                {
                    // Pass the status to the view
                    this.view.ViewData["Status"] = "Login succedded.";
                    // Show the search form
                    this.ShowSearchView();
                }
                else
                {
                    // Pass the status to the view
                    this.view.ViewData["Status"] = "Login failed.";
                }
                // Notify the view of the changes to the status
                this.view.UpdateView("Status");
            }

            if (key == "Exit")
            {
                Application.Exit();           
            }           
        }

        private void ShowSearchView()
        {          
            this.Navigator.Navigate<SearchController>();
        }
    }
}
